package com.example.demo.Controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeWapPayRequest;


import com.example.demo.bean.Message;
import com.example.demo.bean.Order;
import com.example.demo.bean.OrderExample;
import com.example.demo.bean.User;
import com.example.demo.config.AlipayConfig;
import com.example.demo.mapper.OrderMapper;
import com.example.demo.service.AdministratorServerce;
import com.example.demo.service.MessageService;
import com.example.demo.service.SelectHotellInformationService;
import com.example.demo.service.impl.OrderServiceimpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;


@Controller

public class RoomControler {

    @Autowired
    private SelectHotellInformationService selectHotellInformationService;

    @Autowired
    private AdministratorServerce administratorServerce;
@Autowired
    MessageService messageService;
    @Autowired OrderMapper orderMapper;

    @RequestMapping("/showRoom")
    //@RequestParam("userName")String userName, HttpServletRequest request, request.setAttribute("userName",userName);System.out.println(userName);
    public String hello(Model model, HttpServletRequest request) throws ParseException {
        //request.getSession().setAttribute("userName",userName);
        Integer hotel_id = 8363;
        if (request.getParameter("hotel_id") != null) {
            hotel_id = Integer.parseInt(request.getParameter("hotel_id"));
        }
        List<Map> list = selectHotellInformationService.selectRoomByHotellID(hotel_id);

        if (request.getParameter("startDate") != null) {
            String startDateS = request.getParameter("startDate");
            String lastDateS = request.getParameter("lastDate");

            startDateS = startDateS.replaceAll("/", "-");
            String[] split = startDateS.split("-");
            startDateS = split[2] + "-" + split[0] + "-" + split[1];
            System.out.println(startDateS);

            lastDateS = lastDateS.replaceAll("/", "-");
            split = lastDateS.split("-");
            lastDateS = split[2] + "-" + split[0] + "-" + split[1];
            System.out.println(lastDateS);

            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

            Date startDate = simpleDateFormat.parse(startDateS);
            Date lastDate = simpleDateFormat.parse(lastDateS);

            Map<String, Object> map = new HashMap<>();
            map.put("startDate", startDate);
            map.put("lastDate", lastDate);
            map.put("hotel_id", hotel_id);

            System.out.println(map.get("startDate"));
            list = selectHotellInformationService.selectRoom(map);
            for (Map r : list) {
                System.out.print(r.get("room_id") + "-");
                System.out.print(r.get("COUNTER"));
            }

            model.addAttribute("rooms", list);
        } else {
            model.addAttribute("rooms", list);
        }
        List<Message> messages = messageService.findMessagebyhotel(hotel_id);
        request.getSession().setAttribute("hotel_id", hotel_id);
        model.addAttribute("messages", messages);
        System.out.println("_____________________");
        System.out.println(messages.get(0).getMessage() + "+" + messages.get(0).getMessageRoomName());
        return "open/showRoom";
    }

    @RequestMapping("evalute")
    public  String toevalute(@RequestParam(value = "hotel_id")int hotelId, ModelMap modelMap, User user, HttpServletRequest request) {
        List<Message> messages = messageService.findMessagebyhotel(hotelId);
        request.getSession().setAttribute("hotel_id", hotelId);
        modelMap.addAttribute("messages", messages);
        System.out.println("_____________________");
        System.out.println(messages.get(0).getMessage() + "+" + messages.get(0).getMessageRoomName());
        return "open/showRoom";
    }


        @RequestMapping("/tester")
    public String opend(String name, Model model) {
        System.out.println("????");
        System.out.println(name);
        model.addAttribute("name", name);
        return "open/tester";
    }

    @RequestMapping("nihao")
    public String nihao() {
        return "open/pay";
    }


    @RequestMapping("/pay")
    public void pay(HttpServletResponse response, String WIDout_trade_no, String WIDsubject, String WIDtotal_amount, String WIDbody, Model model, HttpServletRequest request) {
        System.out.println("nihao");
        try {
            //订单编号 必填
            String out_trade_no = new String(WIDout_trade_no.getBytes("ISO-8859-1"), "UTF-8");
            // 订单名称，必填
            String subject = new String(WIDsubject.getBytes("ISO-8859-1"), "UTF-8");
            System.out.println(subject);
            // 付款金额，必填
            String total_amount = new String(WIDtotal_amount.getBytes("ISO-8859-1"), "UTF-8");
            // 商品描述，可空
            String body = new String(WIDbody.getBytes("ISO-8859-1"), "UTF-8");
            request.getSession().setAttribute("WIDout_trade_no",out_trade_no);
            System.out.println(out_trade_no);
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        // 超时时间 可空
        String timeout_express = "2m";
        // 销售产品码 必填
        String product_code = "QUICK_WAP_WAY";
        /**********************/
        // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
        //调用RSA签名方式

        AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
        AlipayTradeWapPayRequest alipay_request = new AlipayTradeWapPayRequest();

        // 封装请求支付信息

        AlipayTradeWapPayModel model2 = new AlipayTradeWapPayModel();
        model2.setOutTradeNo(WIDout_trade_no);
        model2.setSubject(WIDsubject);
        model2.setTotalAmount(WIDtotal_amount);
        model2.setBody(WIDbody);
        model2.setTimeoutExpress(timeout_express);
        model2.setProductCode(product_code);
        alipay_request.setBizModel(model2);
        // 设置异步通知地址
        alipay_request.setNotifyUrl(AlipayConfig.notify_url);
        // 设置同步地址
        alipay_request.setReturnUrl(AlipayConfig.return_url);

        // form表单生产
        String form = "";
        try {
            // 调用SDK生成表单

            form = client.pageExecute(alipay_request).getBody();
            System.out.print(form);


            response.setContentType("text/html;charset=" + AlipayConfig.CHARSET);
            try {
                response.getWriter().write(form);
                response.getWriter().flush();
                response.getWriter().close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }//直接将完整的表单html输出到页面


            String insert = "insert into t_order set id=? time=? uid= rid=? startDate=? lastDate=?";


            System.out.println(form);
        } catch (AlipayApiException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    @RequestMapping("/payReturn")
    public String payReturn(HttpServletRequest request) {
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //   可能不需要注释    valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号

       String WIDout_trade_no=(String) request.getSession().getAttribute("WIDout_trade_no");
        System.out.println();
        System.out.println(WIDout_trade_no);
        System.out.println();
        OrderExample example = new OrderExample();
        OrderExample orderExample = new OrderExample();
       Order order = new Order();
                  order.setState("已支付");
        orderExample.createCriteria().andOrdernumNotEqualTo(WIDout_trade_no);
        orderMapper.updateByExampleSelective(order, orderExample);

    /*    OrderServiceimpl orderService = new OrderServiceimpl();
        Order order = new Order();
        order.setState("已支付");
        order.setOrdernum(WIDout_trade_no);
        orderService.updateOrderStatus(order);*/
        //支付宝交易号
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//
        //计算得出通知验证结果
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        String out_trade_no = null;
        String trade_no = null;
        boolean verify_result = true;
        try {
            out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");


            verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }


        System.out.println(out_trade_no + "-" + trade_no);
        if (verify_result) {//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码
            //该页面可做页面美工编辑

            System.out.println("验证成功<br />");
            //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

            //////////////////////////////////////////////////////////////////////////////////////////
        } else {
            //该页面可做页面美工编辑

            System.out.println("验证失败");
        }
        return "index";
    }

    @RequestMapping("/serch")
    public String serch(HttpServletRequest request, HttpServletResponse response) {

        return "tester";
    }


    @RequestMapping("refresh")
    public String globalRefresh(Model model) {
        List<Map<String, String>> lists = new ArrayList<>();


        Map<String, String> map = new HashMap<>();
        map.put("author", "曹雪芹");
        map.put("title", "《红楼梦》");
        map.put("url", "www.baidu.com");
        lists.add(map);

        model.addAttribute("refresh", "我不会被刷新");
        model.addAttribute("title", "我的书单");
        model.addAttribute("books", lists);
        model.addAttribute("begin", 5);
        model.addAttribute("end", 9);
        model.addAttribute("now", 7);
        return "open/test";
    }

    @RequestMapping("refresh/local")
    public String localRefresh(Model model) {
        List<Map<String, String>> lists = new ArrayList<>();
        Map<String, String> map = new HashMap<>();
        map.put("author", "罗贯中");
        map.put("title", "《三国演义》");
        map.put("url", "www.baidu.com");
        lists.add(map);
        model.addAttribute("title", "我的书单");
        model.addAttribute("books", lists);
        System.out.println("asd");
        // "test"是test.html的名，        // "table_refresh"是test.html中需要刷新的部分标志,        // 在标签里加入：th:fragment="table_refresh"        return "test::table_refresh";    }
        return "open/test::table_refresh";
    }

    @RequestMapping("go")
    public String go(HttpServletRequest request, Model model) {
        String keywords = "退款";
        if (request.getParameter("keywords") != null) {
            keywords = request.getParameter("keywords");
            System.out.println(keywords);
        }
        List<Map> lists = administratorServerce.findLike(keywords);
        for (Map list : lists) {
            System.out.println(list.get("state"));
        }
        model.addAttribute("lists", lists);

        return "open/admin";
    }

    @RequestMapping("findLike")
    public String findLike(HttpServletRequest request, Model model) {
        String keywords = "";
        if (request.getParameter("keywords") != null) {
            keywords = request.getParameter("keywords");
            System.out.println(keywords);
        }
        List<Map> lists = administratorServerce.findLike(keywords);
        for (Map list : lists) {
            System.out.println(list.get("state"));

        }


        model.addAttribute("lists", lists);

        return "open/admin::table_refresh";
    }

    @RequestMapping("agree")
    public String argee(HttpServletRequest request, Model model) {
        String keywords = "退款";
        String order_id = request.getParameter("order_id");
        int count = administratorServerce.agree(Integer.parseInt(order_id));
        System.out.println(count);
        if (request.getParameter("keywords") != null) {
            keywords = request.getParameter("keywords");
            System.out.println(keywords);
        }
        List<Map> lists = administratorServerce.findLike(keywords);
        for (Map list : lists) {
            System.out.println(list.get("state"));
        }
        model.addAttribute("lists", lists);
        return "open/admin";
    }

    @RequestMapping("disagree")
    public String disagree(HttpServletRequest request, Model model) {
        String keywords = "退款";
        String order_id = request.getParameter("order_id");
        int count = administratorServerce.disagree(Integer.parseInt(order_id));
        System.out.println(count);
        if (request.getParameter("keywords") != null) {
            keywords = request.getParameter("keywords");
            System.out.println(keywords);
        }
        List<Map> lists = administratorServerce.findLike(keywords);
        for (Map list : lists) {
            System.out.println(list.get("state"));
        }
        model.addAttribute("lists", lists);
        return "open/admin";
    }


    @RequestMapping("goRoom")
    public String goRoom(HttpServletRequest request, Model model) {

        List<Map> lists = administratorServerce.allRoom();
        model.addAttribute("lists", lists);
        model.addAttribute("room","room");
        return "open/admin";
    }


    @RequestMapping("updateById")
    public String updateById(HttpServletRequest request, Model model) {
        String room_id=request.getParameter("room_id");
        String price=request.getParameter("price");
        String bed_type=request.getParameter("bed_type");

        System.out.println(room_id+price);
        Map<String, Object> map = new HashMap<>();
        map.put("room_id", Integer.parseInt(room_id));
        map.put("price", Integer.parseInt(price));
        map.put("bed_type", bed_type);

        int a=administratorServerce.updateById(map);
        System.out.println(a);
        List<Map> lists = administratorServerce.allRoom();
        model.addAttribute("lists", lists);
        model.addAttribute("room","room");
        for (Map list:lists)
        {
            System.out.println(list.get("bed_type"));
        }
        return "open/admin";
    }
}
